#! /usr/bin/env python
import os, sys, argparse, glob, subprocess
from multiprocessing  import Pool

APP_DIR=os.path.split(os.path.abspath(__file__))[0]

def ignore( file_size= '2M' ):
    open( '.hgignore', 'w' ).write( 'syntax: glob\n*.swp\n' )
    cmd= 'find -type f -size +{size} >> .hgignore'.format( size=file_size )
    print cmd
    os.system( cmd )
    os.system( 'cat .hgignore' )

def update( file_size, msg, no_ignore_file ):
    # hg ignore
    if not no_ignore_file:
        ignore( file_size )

    # hg add remove
    cmd= "hg addremove"
    print cmd
    os.system( cmd )

    # hg diff
    #cmd= "hg diff"
    #print cmd
    #os.system( cmd )

    # hg ci
    cmd= 'hg ci -m "'+ msg+'"'
    print cmd
    os.system( cmd )

    # hg push
    cmd= "hg push" 
    print cmd
    os.system( cmd )

def init( file_size ):
    #hgrc
    hgrc= "[ui]\nusername=qiaonan <qiaonancn@genetics.ac.cn>\n[paths]\ndefault-push=/picb/molsysbio/usr/nqiao/backup/hg/xx.hg\n"

    # hg init
    cmd= "hg init" 
    print cmd
    os.system( cmd )

    # hgrc
    open( ".hg/hgrc", "w" ).write( hgrc )
    os.system( "vim .hg/hgrc" )
    print "write hgrc finished!\nhg init finished!"

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='this script creat the .hgignore file')
    #parser.add_argument('-p', '--program', dest='program', help='which program to run', default='update')
    parser.add_argument('-1', '--init', dest= "init", action='store_true', help='run hg init')
    parser.add_argument('-2', '--ignore', dest= "ignore", action='store_true', help='run hg ignore')
    parser.add_argument('-3', '--update', dest= "update", action='store_true', help='run hg update')
    parser.add_argument('-s', '--size', dest='file_size', help='file size to ignore', default='2M')
    parser.add_argument('-m', '--msg', dest='msg', help='msg for check in', default='update')
    parser.add_argument('-n', '--no-ignore-file', dest= "no_ignore_file", action='store_true')
    op= parser.parse_args()
    if op.init:
        init( op.file_size  )
    elif op.ignore:
        ignore( op.file_size  )
    elif op.update:
        update( op.file_size, op.msg, op.no_ignore_file )
    else:
        print( "please see help" )

